from flask import Blueprint, request, jsonify, session, render_template
from datetime import datetime
from app.extensions import db
from app.models.user import LoveList, CoupleRelationship, User
from app.routes.api import login_required, login_required_html

# 假设蓝图名为love_list_bp，需在app中注册
love_list_bp = Blueprint('love_list_bp', __name__)


def get_user_relationship(user_id):
    """获取用户当前有效的情侣关系（已确认）"""
    return CoupleRelationship.query.filter(
        ((CoupleRelationship.user1_id == user_id) |
         (CoupleRelationship.user2_id == user_id)) &
        (CoupleRelationship.status == 'accepted')
    ).first()


@love_list_bp.route('/api/love-list', methods=['GET'])
@login_required
def get_love_lists():
    """获取当前用户的所有恋爱清单（私有+共享）"""
    user_id = session['user_id']
    relationship = get_user_relationship(user_id)

    # 查询条件：自己的私有项 + 共享给自己情侣关系的项
    query = (
        LoveList.query.filter_by(user_id=user_id)  # 自己的所有项
        .union(  # 合并查询
            LoveList.query.filter(
                LoveList.is_shared == True,
                LoveList.relationship_id == (relationship.id if relationship else -1)
            )
        )
    ).order_by(LoveList.created_at.desc())

    love_items = query.all()

    # 格式化返回数据
    return jsonify([{
        'id': item.id,
        'content': item.content,
        'is_completed': item.is_completed,
        'completed_at': item.completed_at.isoformat() if item.completed_at else None,
        'image_url': item.image_url or '',
        'is_shared': item.is_shared,
        'created_by': {
            'id': item.user_id,
            'nickname': User.query.get(item.user_id).nickname or '未知用户'
        },
        'created_at': item.created_at.isoformat(),
        'updated_at': item.updated_at.isoformat()
    } for item in love_items])


@love_list_bp.route('/api/love-list', methods=['POST'])
@login_required
def add_love_item():
    """添加新的恋爱清单项（支持私有/共享）"""
    user_id = session['user_id']
    data = request.json

    # 验证必填字段
    if not data.get('content'):
        return jsonify({'status': 'error', 'message': '清单内容不能为空'}), 400

    # 处理共享逻辑
    is_shared = data.get('is_shared', False)
    relationship_id = None

    if is_shared:
        # 检查是否有已确认的情侣关系
        relationship = get_user_relationship(user_id)
        if not relationship:
            return jsonify({
                'status': 'error',
                'message': '无法共享清单，您尚未建立情侣关系'
            }), 400
        relationship_id = relationship.id

    # 创建新项
    new_item = LoveList(
        user_id=user_id,
        content=data['content'],
        is_shared=is_shared,
        relationship_id=relationship_id,
        image_url=data.get('image_url')  # 可选图片
    )

    db.session.add(new_item)
    db.session.commit()

    return jsonify({
        'status': 'success',
        'message': '清单添加成功',
        'item_id': new_item.id
    })


@love_list_bp.route('/api/love-list/<int:item_id>', methods=['PUT'])
@login_required
def update_love_item(item_id):
    """更新恋爱清单项（内容/完成状态）"""
    user_id = session['user_id']
    item = LoveList.query.get_or_404(item_id)

    # 权限校验
    if not item.is_operable_by(user_id):
        return jsonify({'status': 'error', 'message': '无权修改此清单'}), 403

    data = request.json

    # 更新内容
    if 'content' in data:
        item.content = data['content']

    # 更新图片
    if 'image_url' in data:
        item.image_url = data['image_url']

    # 更新完成状态
    if 'is_completed' in data:
        item.is_completed = data['is_completed']
        # 记录完成时间（首次标记完成时）
        if data['is_completed'] and not item.completed_at:
            item.completed_at = datetime.utcnow()
        # 取消完成时清空时间
        elif not data['is_completed']:
            item.completed_at = None

    # 更新共享状态（需额外校验）
    if 'is_shared' in data:
        new_shared_status = data['is_shared']
        if new_shared_status and not item.relationship_id:
            # 从私有转为共享：需验证情侣关系
            relationship = get_user_relationship(user_id)
            if not relationship:
                return jsonify({
                    'status': 'error',
                    'message': '无法共享清单，您尚未建立情侣关系'
                }), 400
            item.relationship_id = relationship.id
        item.is_shared = new_shared_status

    db.session.commit()
    return jsonify({'status': 'success', 'message': '清单已更新'})


@love_list_bp.route('/api/love-list/<int:item_id>', methods=['DELETE'])
@login_required
def delete_love_item(item_id):
    """删除恋爱清单项"""
    user_id = session['user_id']
    item = LoveList.query.get_or_404(item_id)

    # 权限校验
    if not item.is_operable_by(user_id):
        return jsonify({'status': 'error', 'message': '无权删除此清单'}), 403

    db.session.delete(item)
    db.session.commit()
    return jsonify({'status': 'success', 'message': '清单已删除'})


#@love_list_bp.route('/api/love-list/statistics', methods=['GET'])
#@login_required
#def get_love_statistics():
#    """获取恋爱清单统计（进度展示）"""
#    user_id = session['user_id']
#    relationship = get_user_relationship(user_id)

#    total = LoveList.query.filter(
#        (LoveList.user_id == user_id) |
#        (LoveList.is_shared == True and
#         LoveList.relationship_id == (relationship.id if relationship else -1))
#    ).count()

#    completed = LoveList.query.filter(
#        ((LoveList.user_id == user_id) |
#         (LoveList.is_shared == True and
#          LoveList.relationship_id == (relationship.id if relationship else -1))) &
#        (LoveList.is_completed == True)
#    ).count()

#    return jsonify({
#        'total': total,
#        'completed': completed,
#        'progress': round(completed / total * 100, 1) if total > 0 else 0
#    })




@love_list_bp.route('/api/love-list/statistics', methods=['GET'])
@login_required
def get_love_statistics():
    """获取恋爱清单统计
    - 无情侣关系：计算自己的所有项目（私有+共享）
    - 有情侣关系：计算自己的所有项目 + 情侣的共享项目
    """
    user_id = session['user_id']
    relationship = get_user_relationship(user_id)
    
    if relationship:
        # 有情侣关系：自己的所有项目 + 情侣的共享项目
        # 自己的所有项目
        own_items = LoveList.query.filter_by(user_id=user_id)
        
        # 情侣的共享项目
        partner_shared_items = LoveList.query.filter(
            LoveList.is_shared == True,
            LoveList.relationship_id == relationship.id,
            LoveList.user_id != user_id  # 排除自己的项目（避免重复计算）
        )
        
        # 合并查询计算总数
        total = own_items.union(partner_shared_items).count()
        
        # 已完成项目
        own_completed = LoveList.query.filter_by(
            user_id=user_id,
            is_completed=True
        )
        
        partner_completed = LoveList.query.filter(
            LoveList.is_shared == True,
            LoveList.relationship_id == relationship.id,
            LoveList.user_id != user_id,
            LoveList.is_completed == True
        )
        
        completed = own_completed.union(partner_completed).count()
    else:
        # 没有情侣关系：只计算自己的所有项目
        total = LoveList.query.filter_by(user_id=user_id).count()
        completed = LoveList.query.filter_by(
            user_id=user_id,
            is_completed=True
        ).count()

    return jsonify({
        'total': total,
        'completed': completed,
        'progress': round(completed / total * 100, 1) if total > 0 else 0
    })



@love_list_bp.route('/lovelist')
@login_required_html
def couple_page():
    """渲染情侣空间页面"""
    return render_template('lovelist.html')
